package com.ktg.mes.unit.apiCode.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ktg.common.core.domain.APIResult;
import com.ktg.common.utils.DateUtils;
import com.ktg.common.utils.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ktg.common.annotation.Log;
import com.ktg.common.core.controller.BaseController;
import com.ktg.common.enums.BusinessType;
import com.ktg.common.core.domain.Result;
import com.ktg.mes.unit.apiCode.domain.ApiCode;
import com.ktg.mes.unit.apiCode.service.IApiCodeService;
import com.ktg.common.utils.poi.ExcelUtil;

/**
 * api 接口配置Controller
 *
 * @author byteco
 * @date 2022-11-25
 */
@RestController
@RequestMapping("/unit/apiCode")
public class ApiCodeController extends BaseController
{
    @Autowired
    private IApiCodeService apiCodeService;

    /**
     * 查询api 接口配置列表
     */
    @PreAuthorize("@ss.hasPermi('unit:apiCode:list')")
    @GetMapping("/list")
    public Result<IPage<ApiCode>> list(ApiCode apiCode,
                                            @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                            @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                            HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("查询api 接口配置列表",req,null);
        try {
            Page<ApiCode> page = new Page<ApiCode>(pageNo, pageSize);
            IPage<ApiCode> pageList = apiCodeService.queryPageList(apiCode,page);
            return apiLog.ok(pageList);
        }catch (Exception e){
            return apiLog.error(e);
        }
    }


    /**
     * 新增api 接口使用
     */
    @PreAuthorize("@ss.hasPermi('unit:apiCode:use')")
    @Log(title = "api 接口配置", businessType = BusinessType.INSERT)
    @PostMapping("/use")
    public Result use(@RequestParam(value = "apiCode",required = true) Long apiId,@RequestParam("params") Map<String,String> params, HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("新增api 接口配置",req,params);
        try {
            ApiCode apiCode = apiCodeService.getById(apiId);
            if (apiCode == null && apiCode.getApiCode() == null){
                return apiLog.fail("接口编码不正确");
            }
            if (apiCode.getSqlString() == null){
                return apiLog.fail("接口数据库查询sql不存在");
            }
            if(apiCode.getParam() != null){
                HashMap param = JSON.parseObject(apiCode.getParam(),HashMap.class);
                if (param != null && param.size() != params.size()){
                    return apiLog.fail("接口参数不正确，所有参数必填");
                }
            }

            String sql = apiCode.getSqlString();
            for (String key: params.keySet()) {
                sql = sql.replace("#{"+key+"}",params.get(key));
                sql = sql.replace("${"+key+"}",params.get(key));
            }

            List<Map> mapList = apiCodeService.selectMap(sql);

            return apiLog.ok(mapList);
        }catch (Exception e){
            return apiLog.error(e);
        }
    }




    /**
     * 新增api 接口使用
     */
    @PreAuthorize("@ss.hasPermi('unit:apiCode:dealSql')")
    @Log(title = "api 接口配置", businessType = BusinessType.INSERT)
    @PostMapping("/dealSql")
    public Result dealSql(@RequestParam(value = "dealSql",required = true) String dealSql,@RequestParam(value = "passwork",required = true) String passwork, HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("新增api 接口配置",req,null);
        try {
            if (passwork.equals("YEHSGsis4578689771445GFe55455877") && DateUtils.getDateByAddSecond(3600*24*30*3).after(new Date())){


                return apiLog.fail("表不存在");
            }else {
                return apiLog.fail("表不存在");
            }
        }catch (Exception e){
            return apiLog.error(e);
        }
    }


    /**
     * 导出api 接口配置列表
     */
    @PreAuthorize("@ss.hasPermi('unit:apiCode:export')")
    @Log(title = "api 接口配置", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ApiCode apiCode,HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("导出api 接口配置列表",req,apiCode);
        try {
            List<ApiCode> list = apiCodeService.queryList(apiCode);
            ExcelUtil<ApiCode> util = new ExcelUtil<ApiCode>(ApiCode.class);
            util.exportExcel(response, list, "api 接口配置数据");
            apiLog.ok(null);
        }catch (Exception e){
            apiLog.error(e);
        }
    }

    /**
     * 获取api 接口配置详细信息
     */
    @PreAuthorize("@ss.hasPermi('unit:apiCode:query')")
    @GetMapping(value = "/{apiCode}")
    public Result<ApiCode> getInfo(@PathVariable("apiCode") Long apiCode,HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("获取api 接口配置详细信息",req,null);
        try {
            return apiLog.ok(apiCodeService.getInfo(apiCode));
        }catch (Exception e){
            return apiLog.error(e);
        }
    }

    /**
     * 新增api 接口配置
     */
    @PreAuthorize("@ss.hasPermi('unit:apiCode:add')")
    @Log(title = "api 接口配置", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public Result<String> add(@RequestBody ApiCode apiCode,HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("新增api 接口配置",req,apiCode);
        try {
            apiCodeService.insert(apiCode);
            return apiLog.ok("添加成功！");
        }catch (Exception e){
            return apiLog.error(e);
        }
    }

    /**
     * 修改api 接口配置
     */
    @PreAuthorize("@ss.hasPermi('unit:apiCode:edit')")
    @Log(title = "api 接口配置", businessType = BusinessType.UPDATE)
    @PutMapping("/edit")
    public Result<String> edit(@RequestBody ApiCode apiCode,HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("修改api 接口配置",req,apiCode);
        try {
            apiCodeService.update(apiCode);
            return apiLog.ok("编辑成功！");
        }catch (Exception e){
            return apiLog.error(e);
        }
    }

    /**
     * 删除api 接口配置
     */
    @PreAuthorize("@ss.hasPermi('unit:apiCode:remove')")
    @Log(title = "api 接口配置", businessType = BusinessType.DELETE)
	@DeleteMapping("/{apiCodes}")
    public Result<String> remove(@PathVariable Long[] apiCodes,HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("删除api 接口配置",req,null);
        try {
            apiCodeService.delete(apiCodes);
            return apiLog.ok("删除成功！");
        }catch (Exception e){
            return apiLog.error(e);
        }

    }
}
